package com.lalosoft.gastostarjetaweb.dao;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.lalosoft.gastostarjetaweb.model.Email;
import com.lalosoft.gastostarjetaweb.pmf.PMF;

public class EmailDao {
	
	public static void saveEmail(Email email){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			pm.makePersistent(email);
		} finally {
			pm.close();
		}
	}
	
	public static List<Email> findAll(PersistenceManager pm){
		List<Email> emails = null;
		Query q = pm.newQuery(Email.class);
		emails = (List<Email>)q.execute();
		return emails;
	}
	
	public static List<Email> findByState(String state){
		List<Email> emails = new ArrayList<Email>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			Query q = pm.newQuery(Email.class);
			List<Email> list = (List<Email>)q.execute();
			if(list.size() > 0){
				for(Email temp : list){
					if(temp.getEstado().equals(state)){
						emails.add(temp);
					}
				}
			}
		} finally {
			pm.close();
		}
		return emails;
	}
	
	public static void deleteAll(){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			pm.deletePersistentAll(Email.class);
		} finally {
			pm.close();
		}
	}
	
	public static void deleteEmail(Long id){
		Email emailToDelete = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			Query q = pm.newQuery(Email.class);
			List<Email> list = (List<Email>) q.execute();
			if(list.size() > 0){
				for(Email temp : list){
					if(temp.getId().equals(id)){
						emailToDelete = temp;
					}
				}
				pm.deletePersistent(emailToDelete);
			}
		} finally {
			pm.close();
		}
	}
	
	public static Email findById(Long id){
		Email email = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			Query q = pm.newQuery(Email.class);
			List<Email> list = (List<Email>) q.execute();
			if(list.size() > 0){
				for(Email temp : list){
					if(temp.getId().equals(id)){
						email = temp;
					}
				}
			}
		} finally {
			pm.close();
		}
		return email;
	}

}
